import random
import sys
import time

from libs.action import WebDriverAction
from libs.farm_helper import FarmHelper
from libs.game import Game
from libs.movement import Movement
from libs.log import Log
from libs.task_helper import TaskHelper
from libs.window import AdsWindow
from libs import config


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Farm')
    parser.add_argument('--soil_id', type=int, help="土地ID")
    parser.add_argument('--farm_item', type=str, help="种植物品")

    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)
    user_id = args.user_id

    soil_id = args.soil_id
    farm_item_key = args.farm_item

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver)
        movement = Movement(driver)
        log = Log(user_id)
        farm_helper = FarmHelper(driver, user_id, farm_item_key, soil_id)

        game.enter_game()
        action.escape()
        game.snapshot(user_id, 'farm start')

        prepare_fail = False
        total_round = random.randint(2, 5)
        for farm_round in range(total_round):
            if farm_helper.round_stop:
                break

            log.info(f"round {farm_round}/{total_round}, coin={game.get_coin()}")
            game.collect_mail()
            if farm_helper.prepare_farm():
                farm_helper.goto_farm_position()
                try:
                    farm_helper.farm()
                except Exception as e:
                    log.debug('exception occurred, refresh and retry')
                    print(e)
                    driver.refresh()
                    time.sleep(5)
                    game.enter_game()
                    farm_helper.farm()
            else:
                if prepare_fail:
                    break
                else:
                    prepare_fail = True

        account = config.get_account(user_id)
        config_key = f'farm_{soil_id}'
        if config_key in account:
            new_farm_item_key = account.get(config_key)
            if new_farm_item_key == 'clover':
                task_helper.farm(soil_id, new_farm_item_key, delay_seconds=random.randint(60 * 60 * 6, 60 * 60 * 6))
            else:
                # 6-8小时
                task_helper.farm(soil_id, new_farm_item_key, delay_seconds=random.randint(60 * 60 * 6, 60*60*8))
        task_helper.task_success()

    except Exception as e:
        task_helper.task_fail()
        task_helper.farm(soil_id, farm_item_key, retry=True)
        raise e
